package com.appspot.zarm.game;

import java.util.ArrayList;
import java.util.List;

import com.appspot.zarm.transfer.GameState;

/**
 * This class is the base class for the games. 
 * It is used for the game identification in the container of games.
 * For that purpose all the games ancestors have a pair or more objects having sessionId of all players.
 * To identify game you can use both sessionId.  
 * @author Zhardzetski
 *
 */
public abstract class Game {
	private List<Player> players;

	public Game() {
		players = new ArrayList<Player>();
	}
	
	public boolean hasPlayer(Player player) {
		for (Player p: players) {
			if (p.getId().equals(player.getId())) {
				return true;
			}
		}
		return false;
	}

	public void addPlayer(Player player) {
		players.add(player);
	}
	
	public Player getPlayerOne() {
		return players.get(0);
	}
	
	public Player getPlayerTwo() {
		return players.get(1);
	}
	
	/**
	 * Get player by id. It may be both playerOne as playerTwo, so select appropriate one using id.
	 * @param id is an identifier
	 * @return Player
	 */
	public Player getPlayerById(String id) {
		for (Player player: players) {
			if (player != null && player.getId().equals(id)) {
				return player;
			}
		}
		return null;
	}
	
	/**
	 * For each player we can find rival using player`s id.
	 * @param user
	 * @return
	 */
	public Player getRival(Player player) {
		List<Player> rivals = getRivals(player);
		if (rivals.size() > 0 ){
			return rivals.get(0);
		} else {
			return null;
		}
	}

	public List<Player> getRivals(Player player){
		List<Player> rivals = new ArrayList<Player>();
		for (Player p: players) {
			if (p.isRobot() || !p.getId().equals(player.getId())) {
				rivals.add(p);
			}
		}
		return rivals;
	}
	
	public abstract GameState getGameState();
}
